package com.liujie.controller;

import com.liujie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
import java.util.logging.Filter;

/**
 * 文件上传下载通用的控制器
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${simu.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//获取上传文件的后缀
        String fileName = UUID.randomUUID()+suffix;//随机生成文件名

        //判断原始目录是否存在，不存在需要创建
        File dir=new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }

        try {
            file.transferTo(new File(basePath+fileName));//将文件转存
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info(file.toString());
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //通过字节输入流拿到文件
            FileInputStream fileInputStream=new FileInputStream(new File(basePath+name));
            //通过字节输出流将文件写到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //设置写回文件类型
            response.setContentType("image/jpeg");

            //向浏览器写数据
            int len=0;
            byte[] b=new byte[1024];
            while ((len=fileInputStream.read(b))!=-1){
                outputStream.write(b,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
